<?php

namespace app\mall\service;

// 订单处理
use app\common\self\SelfRedis;
use app\common\model\Config;
use app\common\self\MyJob;
use app\live\model\LiveBroadcast;
use app\live\model\LiveBroadcastGoods;
use app\mall\model\Activity as ModelActivity;
use app\mall\model\ActivityLog;
use app\mall\model\Goods;
use app\mall\model\GoodsAttr;
use app\myself\Bc;
use app\myself\WeixinPay;
use app\order\model\Order;
use app\order\model\OrderGoods;
use app\order\model\OrderInfo;
use app\order\model\PayLog;
use app\share\model\UserShareOrder;
use app\shop\model\ShopCoupon;
use app\shop\model\ShopUsers;
use app\shop\model\UserCoupon;
use app\user\model\User;
use app\user\model\UserAddress;
use app\user\model\UserLevel;
use app\user\model\UserWallet;
use app\user\model\WalletOperationLog;
use app\video\model\Video;
use Exception;
use think\Db;
use think\facade\Db as FacadeDb;

class PayOrder{
    public $bc = null;

    public $vipConfig = null;

    function __construct()
    {
        $this->bc = new Bc();
    }

    /**
     * 前缀-数据验证和拿取
     * @param 路由数据
     */
    public function Verification(&$user,$param)
    {
        $one = Goods::find($param['id']);
        // 验证商品记录
        if(!$one) return ['msg'=> '当前商品记录为空','bool'=>false];
        // 如果有店铺
        if($one->shop_id && $one->shop_id > 0){
            $shopOne = ShopUsers::where([
                'id' => $one->shop_id
            ])->field('apply_status,is_open')->find();
            if($shopOne['apply_status'] != 1)return ['msg'=> '此商品-店铺未通过审核','bool'=>false];
            if($shopOne['is_open'] != 1)return ['msg'=> '此商品-店铺已关闭','bool'=>false];
        }

        // 商品信息判断开始
        if($one->status != 1) return ['msg'=> '商品已下架','bool'=>false];
        // 商品规格-记录
        $goodsAttrModel =  new GoodsAttr();
        if(!$one['attr'] = $goodsAttrModel->getGoodsIdAttrId($param['id'],$param['attr_id'])) return ['msg'=> '没有该规格id','bool'=>false];
        // 商品库存
        if($one['attr']['stock'] < $param['num']) return ['msg'=> '抱歉，当前规格库当前只有：'.$one['attr']['stock']."，当前购买数量为：".$param['num'],'bool'=>false];//return retu_json(400,'抱歉，当前规格库当前只有：'.$one['attr']['stock']."，当前购买数量为：".$num);
        // 是否可以使用购物券支付
        $one['wallet_bool'] = isset($param['wallet']) && $param['wallet'] == 1 && $one->ticket > 0 && $one->is_use == 1;
        $user['userWallet'] = null;
        // 如果有使用购物券 或者 使用了 余额支付 拿取钱包表
        if($one['wallet_bool'] || (isset($param['pay_type']) && $param['pay_type'] == 2)) $user['userWallet'] = UserWallet::where('uid',$user->id)->find();
        // 商品价格
        $one['price'] = $one['attr']['price'];
        // 商品的自购省比例
        $user['purchase_ratio'] = $one->is_activity == 0 && $one['is_sale'] == 1 ? 1 : 0 ;
        $user['userWallet_balance'] = 0;
        // 是否使用了优惠券
        if(isset($param['coupon']) && $param['coupon'] >= 1 && $one->shop_id)$this->getCoupon($one,$param);
        // 余额支付
        if($param['pay_type'] == 2){
            if(!isset($user['userWallet'])) $user['userWallet'] = UserWallet::where('uid',$user->id)->find();
            if(!$user['userWallet']) return retu_json(400,'余额为空');
            // !$user['userWallet']['balance']
            $user['userWallet_balance'] = $user['userWallet']['balance'];
        }
        $one['title_msg'] = '开始处理逻辑';
        return ['bool'=>true, 'msg'=> '验证ok','data'=>$one];
    }

    /**
     * 获取到基本数据 -  金额计算 比例等
     */
    public function getMoneyNum(&$one,$user,$param){
        // 商品总额
        $one['sum_price'] = $this->bc->calcMul($one['price'],$param['num'],2);
        // 总支付价格
        $one['money'] = $this->bc->calcAdd($this->bc->calcMul($one['price'],$param['num'],2),$one->freight/100,2);
        // 购物券余额  -  商品当前可以使用的购物券金额
        $volume_money = 0;
        $one['volume_price_money'] = 0;
        //  如果使用了购物券  &&  当前购物券大于0
        if($one['wallet_bool'] && $user['userWallet'] && $user['userWallet']['volume_balance']){
            $volume_money = $user['userWallet']['volume_balance'] / 100;
            $one['volume_price_money'] = $this->bc->calcMul( $one->ticket / 100, $one['price'] * $param['num'],2);
        }
        // 如果是活动 则 自购省比例设置为0 或者如果当前是直播商品 或者 当前商品没有开启分销
        if($one->is_sale == 0 || $one->is_activity == 1 || (isset($one['switch_num']) && $one['switch_num'] == 6) ) $user['purchase_ratio'] = 0;
        // 自购省计算
        $one['purchase_price'] = $this->bc->calcMul($one['price'],$user['purchase_ratio']*$param['num'],2);

        $configModel = new Config();
        $configList = $configModel->toData('business');
        // 默认是开启的 - 表示可以同时使用
        $purchase_volume_bool = isset($configList->purchase_volume_bool) && $configList->purchase_volume;
        // 如果使用了购物券 且 后台 配置 不可同时使用
        if($one['volume_price_money'] > 0 && !$purchase_volume_bool) $one['purchase_price'] = 0;

        // 优惠券抵扣金额
        $one['coupon_money'] = 0;

        //有使用优惠券  且 可以使用优惠券 且 当前不是直播商品
        if((!isset($one['switch_num']) || $one['switch_num'] != 6) && $one['userCoupon'] && $one['coupon_bool'] && $one['sum_price'] > $one['userCoupon']['total_amount'] && $one['userCoupon']['amount'] > 0){
            // 必须余总大于 当前优惠券抵扣
            if($one['money'] > $one['userCoupon']['amount'])$one['coupon_money'] = $one['userCoupon']['amount'];
        }
        $one['money'] = $this->bc->calcSub($one['money'],$one['coupon_money'],2);

        $one['money'] = $this->bc->calcSub($one['money'],$one['purchase_price'],2);
        list($one['money'],$one['volume_price_money']) = $this->sumTotalMoney($one['money'],$volume_money,$one['volume_price_money']);
        if($one['volume_price_money'] < 0) $one['volume_price_money'] = 0;
    }

    /**
     * 根据 余总、抵扣券余额，抵扣券金额，算出当前的实际抵扣和实际支付的金额
     * @param $money 余总   全部金额  -  自购省金额（等）
     * @param $wallet 抵扣券余额
     * @param $wallet_money 抵扣券余额当前需要抵扣的金额
     * */
    public function sumTotalMoney($money,$wallet,$wallet_money = 0){
        $shiji_deduct_money = 0;
        // 如果大于抵扣券余额
        if($wallet_money > $wallet) $wallet_money = $wallet;
        if($wallet_money >= $money){
            $wallet_money = $wallet - $money;
            $shiji_deduct_money = $money;
            $money = 0.01;
        }else{
            $money = $money - $wallet_money;
            $shiji_deduct_money = $wallet_money;
            $wallet_money = 0;
        }
        return [$money,$shiji_deduct_money];
    }

    /**
     * 生成订单数据
     */
    public function createOrderData(&$user,&$one,$param){
        // 时间戳
        $one['time'] = time();
        // 生成订单号
        $orn = getNumber();
        $one['orn'] = $orn;
        $orderData = [
            'uid' => $user->id, // 用户id
            'type' => 1, // 订单类型 1-常规订单，2-活动订单（拼团），3-直播订单'
            'order_sn' => $orn, // 订单号
            'aid' => 0, // 关联商品的id,
            'addr_id'=> 0, // 收货地址
            'total' => $one['money'] > 0.01 ? $one['money'] * 100 : 0, // 支付总金额
            'freight' => $one->freight * 100, //  运费，单位分
            'add_time' => $one['time'], // 下单时间
            'is_volume' => $one['volume_price_money'] > 0 ? 1 : 0, // 是否使用购物券
            'volume' => $one['volume_price_money'] * 100, // 购物券金额
            'remarks' => isset($param['desc']) ? $param['desc'] : '', // 订单备注
            'pay_type' => $param['pay_type'], // 支付类型
            'receipt_name' => $param['name'],
            'receipt_phone' => $param['phone'],
            'receipt_address' => $param['address'],
            'shop_id' => $one->shop_id,
            'coupon_money' => $one['coupon_money'] * 100,
            'coupon_id' => isset($one['userCoupon']) ? $one['userCoupon']['id'] : 0
        ];
        // 订单详情数据 商品规格一定要存储
        $orderInfoData = [
            'json' => [
                'good_attr' => $one['attr']->toArray(),
                'goods' => [
                    'id'  => $one->id,
                    'name' => $one->toArray()['name'],
                    'ticket' => $one->ticket,
                    'is_sale' => $one->is_sale,
                    'is_use' => $one->is_use,
                    'is_team' => $one->is_team,
                    'status' => $one->status,
                    'title' => $one->title
                ],
                'num'=>$param['num'],
                'params' => $param
            ],
            'balance_money' => $one['money'],
            'pay_type' => $param['pay_type'],
            'purchase_ratio' => $user['purchase_ratio'],
            'purchase_money' => $one['purchase_price'] * 100,
            'volume_ratio' => $one['volume_price_money'] > 0 ? $one->ticket : 0
        ];
        $attr_str = '';
        if($one['attr']['valjson'] && is_array($one['attr']['valjson']))foreach($one['attr']['valjson'] as $k => $v)$attr_str .= "$k:$v ";
        // 订单 商品数据
        $orderGoodsData = [
            'goods_id' => $one->id,
            'attr_id' => $one['attr']['id'],
            'attr_str' => $attr_str,
            'title' => $one['name'], // 商品名称
            'cost' =>  $one['attr']['cost_price'] * 100, // 当前的成本价
            'price' => $one['price'] * 100, // 如果为直播跳转那么 则是直播价 商品价
            'discount_price' => $one['attr']['discount_price'] * 100, // 划线价
            'num' => $param['num'],
            'freight' => $one['freight'] * 100,
            'purchase_money' => $one['purchase_price'] * 100, // 自购省金额
            'purchase_ratio' => $user['purchase_ratio'], // 自购省抵扣比例
            'volume' => $one['volume_price_money'] * 100, // 购物券金额 使用金额
            'volume_ratio' => $one['volume_price_money'] > 0 ? $one->ticket / 100 : 0, // 购物券抵扣比例
            'add_time' => $one['time'],
            'is_sale' => $one->is_sale, // 分销 分享
            'is_team' => $one->is_team, // 累计业绩  累计消费
            'total' => $one['money'] > 0.01 ? $one['money'] * 100 : 0, // 实际付款金额
            'coupon_money' => $one['coupon_money'] * 100,
            'img' => $one['attr']['img'],
            'live_uid' => isset($this->lives_list) && isset($this->lives_list['uid']) ? $this->lives_list['uid'] : 0 // 主播用户
        ];
        // $one['orderData'] = $orderData;
        // $one['orderInfoData'] = $orderInfoData;
        $this->orderData = $orderData;
        $this->orderInfoData = $orderInfoData;
        $this->orderGoodsData = $orderGoodsData;
        return $one;
    }

    /**
     * 会员层级判断
     */
    public function getUserList($levelId){
        if(!$level = UserLevel::where('id',$levelId)->find())return false;
        return $level;
    }

    /**
     * 处理类型判断
     * @param 前端传递的参数
     */
    public function JudgmentType($user,&$one,$param)
    {
        // 默认流程类型 -  常规商品
        $switch_num = 1;
        $switch_type = 'goods';

        // 目前已知情况：  1常规商品，2活动-开团，3活动-开团-入团，4视频-关联商品分享，5商品-分享商品 ， 6 直播商品-直播跳转购买
        $title_msg = '提示信息如下'.($param['pay_type'] == 1 ? '微信支付-' : '余额支付-');
        $time = $one['time'];
        // 视频分享-流程
        $videoBool = isset($param['video_id']) && $param['video_id'];
        // 商品-分享
        $goodBool =  isset($param['puid']) && $param['puid'] > 0;
        //  && !(isset($param['activity_log_id']) && $param['activity_log_id'])
        // 拼团 2- 活动开团处理  ，  3-  开团-入团
        if($one->is_activity == 1){
            $switch_num = 2;
            $switch_type = 'activity_goods_create';
            $activity_log_id = $param['activity_log_id'] ?? false;
            // 拿取拼团活动列表
            $activityModel = new ModelActivity();
            $activityOne =  $activityModel->getActivitysGoods($one->id);
            // 判断该活动是否在活动中
            if($activityOne->status == 1 && $activityOne->end_time > $time){
                $this->orderData['type'] = 2;
                if($param['num'] > 1) return retu_json(400,'拼团数量只能为1');
                // 2 -  活动开团处理
                // 开团记录的基本数据  -  当前
                $activity_logData = [
                    //  'oid' => $orderId, // 订单id
                    'aid' => $activityOne->id, // 活动id
                    'uid' => $user->id, // 用户id
                    'price' => $one['attr']['price'] * 100, // 当前商品的规格价
                    'discount_price' => $one['attr']['discount_price'] * 100, // 当前商品的折扣价
                    'miao' => 0, // 喵呗  单位分
                    'num' => $activityOne->num,
                    'type' => $activityOne->num, // 计算方式  固定值 和 百分比
                    'content' => $activityOne->content ? json_encode($activityOne->content) : $activityOne->content, // 开团计算值
                    'end_time' => $time + $activityOne->hours * 3600, // 拼团结束时间 内
                    'add_time' => $time, // 添加时间
                    'goods_id' => $one->id, // 拼团id
                    'img' => $one['attr']['img']
                ];
                $this->activity_logData = $activity_logData;
                // 3 - 入团
                if($activity_log_id && $activity_log_id > 0){
                    //$activityLogModel =  ActivityLog::find($activity_log_id);
                    $activityLogModel = ActivityLog::where([['aid','=',$activity_log_id],['end_time','>',$time],['astatus','=',0]])->order('add_time asc')->limit(1)->find();
                    // 自己不能入自己的团 结束时间  && 实际参与人数
                    if($activityLogModel && $activityLogModel->uid != $user->id && $activityLogModel->end_time > $time && $activityLogModel->num > $activityLogModel->nums){
                        $one['activityLogModel'] = $activityLogModel;
                        $switch_num = 3;
                        $switch_type = 'activity_goods_add';
                    }
                }
            }
            // 分享- 视频 4 ||  商品分享 5
        }else if($videoBool || $goodBool){
            $desc = '视频分享-商品购买';
            // 视频分享
            if($videoBool){
                $videoOne = Video::where([
                    'id' => $param['video_id'],
                    'status' => 1,
                    'is_delete' => 0
                ])->field('id,uid,type,relation_id')->find();
                $pUser= User::where(['id' => $videoOne->uid,'is_delete' => 0])->field('id,level,is_fictitious,is_proceeds')->find();
                // 存在视频 && 视频关联此商品 && 视频发布者 不等于 当前用户id 且 分享者存在user表
                if($videoOne && $videoOne->type == 1 && $videoOne->relation_id == $one->id && $user->id != $videoOne->uid){
                    $switch_type = 'video_share_goods';
                    $switch_num = 4;
                }
                // 商品分享-流程
            }else if($param['puid'] && $pUser= User::where(['id' => $param['puid'],'is_delete' => 0])->field('id,level,is_fictitious,is_proceeds')->find()){
                // 分享者不等于 购买者
                if($pUser->id != $user->id ){
                    $switch_type = 'user_share_goods';
                    $switch_num = 5;
                    $desc = '用户-商品分享-商品购买';
                }
            }
            // 获取到分享者层级
            if($switch_num > 1 && $pUser['level'] = $this->getUserList($pUser->level)){
                //  分享者的比例
                $pUser = $this->getProportional($pUser);
                if($pUser['share_ratio'] > $user['purchase_ratio']){
                    // 副表-数据 分享订单表-基本数据
                    $UserShareOrderData = [
                        'type' => $switch_num == 4 ? 1 : 2,
                        'puid' => $pUser->id,
                        'uid' => $user->id,
                        'status' => 1, // 代付款
                        'add_time' => $one['time'],
                        'goods_id' => $one->id,
                        'total' => $one['money'] * 100,
                        'p_share_money' => $this->bc->calcMul($pUser['purchase_ratio']*$param['num'],$one['attr']['price'],2) * 100,
                        'self_money' => $this->bc->calcMul($user['purchase_ratio']*$param['num'],$one['attr']['price'],2) * 100,
                        'desc' => $desc
                    ];
                    $this->UserShareOrderData = $UserShareOrderData;
                    $this->orderInfoData['json']['data_list'] = ['puid' => $pUser->id];
                }else{
                    $switch_type = 'goods';
                    $switch_num = 1;
                }
            }
            // 直播分享操作
        }else if($one['liveBroadcastGoodsOne'] && isset($this->UserShareOrderData)){
            $liveUser = User::field('nickname,avatarurl')->find($this->lives_list['uid']-0);
            $this->orderInfoData['json']['lives'] = [
                'live_id' => $this->lives_list['live_id'],
                'uid' => $this->lives_list['uid'],
                'nickname' => $liveUser ? $liveUser->nickname : '风再起时',
                'avatarurl' => $liveUser ? $liveUser->avatarurl : 'https://admin-miaomeimei-1301812909.cos.ap-guangzhou.myqcloud.com/admin/userNickName/2020_09_05/81083_1599301340.jpg',
                'live_goods_id' => $one['liveBroadcastGoodsOne']->id,
                'live_price' => $one['price'],
                'commission' => $this->UserShareOrderData['miao'],
                'commission_rato' => $one['liveBroadcastGoodsOne']->commission,
                'miao'  => $this->UserShareOrderData['miao']
            ];
            $this->UserShareOrderData['total'] = $one['money'] * 100;
            $this->orderData['type'] = 3;
            $switch_num = 6;
            $switch_type = 'lives_goods_add';
        }
        $this->orderInfoData['switch_num'] = $switch_num;
        $one['switch_type'] = $switch_type;
        return $one;
    }

    /**
     * 获取分享者和购买者之间的比例
     */
    public function getUserPuserRatio($user,$puser){
        $user = $this->getProportional($user);
        $puser = $this->getProportional($puser);
        return [$user,$puser];
    }


    /**
     * 获取到比例 体系  ， 自购省比例   分享比例
     */
    public function getProportional(&$user){
        $user['share_ratio'] = $user['level']->share / 100;
        $user['purchase_ratio'] = $user['level']->purchase  / 100;
        // 如果层级等于1  且  有开通购物券vip 399
        /*
        if($user['level']->id == 1 && $user->is_proceeds){
            $volumeConfig = $this->createVipConfig();
            // VIP399-配置信息 注意： 千分比
            if($volumeConfig){
                $user['share_ratio'] = $volumeConfig->share/1000;
                $user['purchase_ratio'] = $volumeConfig->purchase/1000;
            }
        }
         */
        return $user;
    }

    /**
     * 直播中  -  直播中-直播购买 - 处理逻辑
     */
    public function liveSwitchData(&$one,&$user,$param){
        $one['liveBroadcastGoodsOne'] = null;
        // 商品是活动
        if($one->is_activity == 0 && isset($param['lives']) && $param['lives'] == 'lives'){
            // 直播中的商品处理
            $liveBroadcastGoodsModel = new LiveBroadcastGoods();
            // 拿取正在直播中的商品
            if($lives_list = $liveBroadcastGoodsModel->getReGoods($one->id)){
                $lives_list['is_delete'] = 0;
                $liveBroadcastOne = LiveBroadcast::where($lives_list)->field('id')->find();
                if($liveBroadcastOne = LiveBroadcast::where($lives_list)->field('id')->find()){
                    $lives_list['live_id'] = $liveBroadcastOne->id;
                    $this->lives_list =  $lives_list;
                    // 存储直播信息 需要拿取到 主播用户id, 当前直播的列表id,直播商品id
                    if($one['liveBroadcastGoodsOne'] =  LiveBroadcastGoods::where(['goods_id' => $one->id,'is_delete' => 0])->field('id,commission')->find()){
                        $user['purchase_ratio'] = 0;
                        // 单个商品直播价格
                        $one['price'] = $one['attr']['live_price'];
                        $liveBroadcastGoodsOne = $one['liveBroadcastGoodsOne'];
                        // 存储直播中分享的佣金比例
                        $commission = $liveBroadcastGoodsOne ? $this->bc->calcMul($liveBroadcastGoodsOne->commission * $param['num'] , $one['attr']['live_price'],2)  : 0;
                        // 副表-数据 分享订单表-基本数据
                        $UserShareOrderData = [
                            'uid' => $user->id,
                            'puid' => $lives_list['uid'],
                            'status' => 1, // 代付款
                            'add_time' => $one['time'] ? $one['time'] : time(),
                            'goods_id' => $one->id,
                            'total' => 0,
                            'self_money' => $this->bc->calcMul($user['purchase_ratio']*$param['num'],$one['attr']['price'],2)
                        ];
                        $userShareMiao = $this->bc->calcMul($commission, 100);
                        $UserShareOrderData['type'] = 3;
                        $UserShareOrderData['puid'] = $lives_list['uid'];
                        $UserShareOrderData['miao'] =$userShareMiao;
                        $UserShareOrderData['related_id'] = $lives_list['live_id'];
                        $UserShareOrderData['live_price'] = $one['attr']['live_price'] * 100;
                        $UserShareOrderData['live_miao_ratio'] = $liveBroadcastGoodsOne ? $liveBroadcastGoodsOne->commission : 0;
                        $UserShareOrderData['desc'] = '直播商品-直播跳转商品-分享';
                        $this->UserShareOrderData = $UserShareOrderData;
                        $one['switch_num'] = 6;
                        $one['switch_type'] = 'lives_goods_add';
                    }
                }
            }
        }
    }

    // 获取到vip配置信息
    public function createVipConfig(){
        if($this->vipConfig) return $this->vipConfig;
        $this->vipConfig = (new Config())->getSrTypes('volumeVip');
        return $this->vipConfig;
    }

    // 数据库操作 等下单流程
    public function startLogic($one, $user,$param){
        // 添加redis
        $sr = new SelfRedis();
        $sr->redis->select(5);
        if($sr->redis->getNx('order_create_'.$user->id))
            return retu_json(400,'等待5秒后尝试');
        //------- 订单表开始 ------
        $orderModel = new Order();
        $orderInfoModel = new OrderInfo();
        $orderGoodsModel = new OrderGoods();
        FacadeDb::startTrans();
        // 异常处理
        try{
            // 限流  - 单个用户 10秒只能生成一笔订单 防止 产生多个订单号
            $sr->redis->setNx('order_create_'.$user->id,$one['orn'],10);
            // 生成订单表
            $orderId = $orderModel->insertGetId($this->orderData);
            if(!$orderId) return retu_json(400,'订单生成失败');
            // // 插入到订单详情表
            $this->orderInfoData['oid'] = $orderId;
            $this->orderInfoData['json'] = json_encode($this->orderInfoData['json']);
            $orderInfoId = $orderInfoModel->insertGetId($this->orderInfoData);
            if(!$orderInfoId)
                return retu_json(400,'订单生成失败11');
            // 插入到订单-商品表
            $this->orderGoodsData['order_id'] = $orderId;
            $orderGoodsId = $orderGoodsModel->insertGetId($this->orderGoodsData);
            if(!$orderGoodsId)
                return retu_json(400,'订单生成失败22');
            // 处理结果的数据
            $return_data = ['msg'=>'ok'];

            // 处理逻辑
            if($one['switch_type'] == 'goods'){

                // 视频分享 -  商品分享
            }else if($one['switch_type'] == 'video_share_goods' || $one['switch_type'] == 'user_share_goods'){
                $this->UserShareOrderData['oid'] = $orderId;
                $UserShareOrderId = UserShareOrder::insertGetId($this->UserShareOrderData);
                if(!$UserShareOrderId)
                    return retu_json(400,'视频分享记录失败，重新尝试');
                // 拼团  -  创建
            }else if($one['switch_type'] == 'activity_goods_create'){
                // 拼团列表模型-插入一条新的记录
                $ActivityLogModel = new ActivityLog();
                // //  'oid' => $orderId, // 订单id
                if(isset($this->activity_logData))
                    $this->activity_logData['oid'] = $orderId;
                $ActivityLogId = $ActivityLogModel->insertGetId($this->activity_logData);
                if(!$ActivityLogId)
                    return retu_json(400,'生成历史订单错误，请重新查看');
                $return_data['data']['log_id'] = $ActivityLogId;
                // 拼团  - 入团 - 创建
            }else if($one['switch_type'] == 'activity_goods_add'){
                // 拼团列表模型-插入一条新的记录
                $ActivityLogModel = new ActivityLog();
                if(isset($one['activityLogModel']) && isset($this->activity_logData)){
                    $this->activity_logData['oid'] = $orderId;
                    $this->activity_logData['pid'] = $one['activityLogModel']->id;
                    $ActivityLogId = $ActivityLogModel->insertGetId($this->activity_logData);
                    $return_data['data']['log_id'] = $ActivityLogId;
                }
                // 直播添加
            }else if($one['switch_type'] == 'lives_goods_add'){
                $this->UserShareOrderData['oid'] = $orderId;
                $UserShareOrderId = UserShareOrder::insertGetId($this->UserShareOrderData);
                if(!$UserShareOrderId) return retu_json(400,'用户直播商品记录失败，重新尝试');
            }
            $return_data['data']['pay_type'] = $param['pay_type'];
            // 微信支付
            if($param['pay_type'] == 1){
                // 调用微信支付返回信息
                // $user->is_fictitious == 1 虚拟用户
                $a = new WeixinPay($user->openid,$one['orn'].'0','订单支付',$user->is_fictitious == 1 ? 0.01 : $one['money']); // $money $user->is_fictitious == 1 ? 0.01 : $one['money']
                $pay = $a->pay(); //下单获取返回值
                if(!$pay || !$pay['code'])
                    return retu_json(400,isset($pay['msg']) ? $pay['msg'] : '`麻烦重新尝试');
                if(isset($pay['data']['appId']))
                    unset($pay['data']['appId']);
                $pay['data']['orderid'] = $one['orn'];
                $return_data['data'] = $pay['data'];
                $return_data['data']['title_msg'] = '';
                $return_data['data']['pay_type'] = $param['pay_type'];
                $pay_log = PayLog::insertGetId(['uid'=>$user->id,'oid'=>$orderId,'orn'=>$one['orn'].'0','request'=>json_encode($return_data),'explain'=>$one['title_msg'],'ip'=>0]);//写入支付记录
                # 微信支付需要推送到队列中
                $configList = Config::where('type','business')->find();
                if($configList && $configObj = json_decode($configList['content'],true))
                    MyJob::pushQueue('OrderPayDelay',['id'=>$orderId],$configObj['overtime'] * 60);
                // 余额支付 - 先扣掉会员的钱  之后  进行 前端回调 处理  或者 redis 队列 执行 -  此处采用 前端回调处理逻辑
            }else{
                if($one['money'] * 100  >  1 && (!$user['userWallet_balance'] || $user['userWallet_balance'] < $one['money'] * 100))
                    return retu_json(400,'当前余额为：'.($user['userWallet_balance']/100).",需要支付的金额为：".($one['money']));
                //Log::write('余额支付开启',$user->id.'---余额---'.$orderId);
                // 写入缓存
                $sr->redis->set('order_pay_'.$one['orn'],1);
                $isRedis = true;
                $return_data['msg'] = '余额支付ok';
                $return_data['data']['orderid'] = $one['orn'];
                $return_data['data']['title_msg'] = $one['title_msg'];
                $return_data['data']['pay_type'] = $param['pay_type'];
                $pay_log = PayLog::insertGetId(['uid'=>$user->id,'oid'=>$orderId,'orn'=>$one['orn'].'0','request'=>json_encode($return_data),'explain'=>$one['title_msg'],'ip'=>0]);//写入支付记录
                if(!$pay_log)
                    return retu_json(400,'支付记录失败');
                // 拿取模型数据
                $orderOrnModel = $orderModel->where('order_sn',$one['orn'])->find();
                $orderInfoIdModel = $orderInfoModel->where('oid',$orderOrnModel->id)->find();
                $list = $orderModel->completeOrder([
                    'orderOrnModel' => $orderOrnModel,
                    'orderInfoModel' => $orderInfoIdModel,
                    'userModel' => $user
                ]);
                if(!$list || !$list['bool'])
                    return retu_json(400,'错误');
                if($one['money'] > 0.01){
                    $okMoney = UserWallet::where('uid',$user->id)->dec('balance',$one['money'] * 100)->update();
                    if(!$okMoney) return retu_json(400,'余额支付错误，麻烦重新尝试');
                }
                # 所有操作  钱包 都需要走钱包表
                if($one['money'] * 100 > 1){
                    $WalletOperationLogData = ['uid'=>$user->id,'reward'=> $one['money'] * 100,'status'=>2,'type'=>1,'extend'=>'order','extend_id'=>$orderOrnModel->id,'describe'=>'订单支付-余额支付','add_time'=>$one['time']];
                    if(!WalletOperationLog::insertGetId($WalletOperationLogData))return retu_json(400,'余额支付，扣除余额-记录失败');
                    # 操作余额 需要记录  余额 支付 金额
                    $balanceLogId = FacadeDb::name('balance_log')->insertGetId(['type' => 2,'uid' =>$user->id,'add_time' => time(),'relation_id' =>  $orderId,'num' => $one['money'] * 100]);
                    if(!$balanceLogId) return retu_json(400,'余额支付，扣除-余额-记录失败，重试');
                }
            }
            if(!$pay_log)
                return retu_json(400,'支付记录更新失败，请重新尝试');
            # 判断当前商品库存的方式  // 拍下减库存 $one
            if($one->is_stock == 1){
                // 商品规格减库存
                if(isset($one['attr']['id']) && $goodsAttrModel = GoodsAttr::find($one['attr']['id']))
                    GoodsAttr::where('id',$one['attr']['id'])->update(['stock' =>  $goodsAttrModel->stock - $param['num'] > 0 ? $goodsAttrModel->stock : 0]);
                // 当前商品减库存
                Goods::where('id',$one->id)->update(['stock' => $one->stock - $param['num'] > 0 ? $one->stock - $param['num'] : 0]);
            }
            # 如果有拼团记录id
            if(isset($ActivityLogId) && $ActivityLogId > 0) $return_data['data']['log_id'] = $ActivityLogId;
            // 提交事务
            FacadeDb::commit();
            return $return_data;
        }catch (Exception $e){
            FacadeDb::rollback();
            // 是否需要删除缓存
            if(isset($isRedis) && $isRedis)
                $sr->redis->del('order_pay_'.$one['orn']);
            return $e->getMessage();
        }
    }

    /**
     * 获取到使用的优惠券 - 此处是判断用户是否使用了优惠券 且 当前商品是否符合当前店铺优惠券情况
     */
    public function getCoupon(&$one,&$param){
        // 默认不满足使用优惠券条件
        $one['coupon_bool'] = false;
        $time = time();
        $userCouponWhere = [
            ['id','=',$param['coupon']],
            ['status','=',0],
            ['start_time','<',$time],
            ['end_time','>',$time],
            ['is_delete','=',0],
            ['shop_id','=',$one->shop_id]
        ];
        if($one['userCoupon'] = UserCoupon::where($userCouponWhere)->find()){
            $one['coupon_bool'] = true;
            // 判断使用类型 如果为指定商品
            if($one['userCoupon']['use_status'] == 2){
                $shopCouponModel = new ShopCoupon();
                $one['coupon_bool'] = $shopCouponModel->getRegGoods($one->id,$one['userCoupon']);
            }
        }
    }


    /**
     *  init 初始化操作
     */
    public function init($user,$verificationData,$param){
        $one = $verificationData['data'];
        // 获取到购买者 的比例
        $user = $this->getProportional($user);
        // 直播中
        $this->liveSwitchData($verificationData['data'],$user,$param);
        // 金额计算
        $this->getMoneyNum($verificationData['data'],$user,$param);
        $test = [
            "单个商品价格" =>  $one['price'],
            "优惠券抵扣金额" => $one['coupon_money'],
            '当前商品的购物券比例' => $one['ticket'] / 100,
            "当前总支付金额" => $one['price'] * $param['num'],
            '需要支付的金额' => $one['money'],
            '购物券抵扣的金额' => $one['volume_price_money'],
            '单个商品可以抵扣的购物券金额' => $one['ticket'] / 100 * $one['price'],
            '自购省抵扣的金额' => $one['purchase_price'],
            '当前-自购省抵扣的比例' => $user['purchase_ratio']
        ];
        // 生成基本-订单数据
        $one = $this->createOrderData($user,$verificationData['data'],$param);
        // 流程分支-类型-处理逻辑
        $this->JudgmentType($user,$one,$param);
        // 数据库创建 - 等 操作开始
        $list = $this->startLogic($one,$user,$param);
        return $list;
    }
}
?>